#include "StdAfx.h"
#include "PCXImage.h"


PCXImage::PCXImage( const std::string filename )
{
	m_filename = filename;
}


PCXImage::~PCXImage( void )
{
}

Imagem* PCXImage::loadPCXImage( void )
{
	Imagem *m_image;
	byte color, r, g, b;	// for palette settings
	byte counter, length;	// for RLE
	unsigned int x, y;		// coordinates of pixel to plot

	imageFile = fopen( m_filename.c_str(), "rb" );
	if( imageFile == NULL )
		exit(1);

	readHeader();
	if( m_header.bitsPerPixel != 8 ) {
		fclose( imageFile );
		exit( 2 );
	}
	if( m_header.nColorPlanes != 1 ) {
		fclose( imageFile );
		exit( 2 );
	}
	if( m_header.magic != 10 ) {
		fclose( imageFile );
		exit( 3 );
	}

	m_image = new Imagem( ( m_header.xEnd - m_header.xStart + 1 ), ( m_header.yEnd - m_header.yStart + 1 ) );

	fseek( imageFile, -768, SEEK_END );
	for( x = 0; x < 256; x++ ) // read palette
	{
		 r = fgetc( imageFile );
		 //r = r >> 2;

		 g = fgetc( imageFile );
		 //g = g >> 2;

		 b = fgetc(imageFile);
		 //b = b >> 2;
		 int rgb = ( r << 16 ) | ( g << 8 ) | b;
		 palette[ x ] = rgb;
	}

	x = m_header.xStart;
	y = m_header.yStart;
	fseek( imageFile, 128, SEEK_SET );
	while( y <= ( m_header.yEnd - m_header.yStart ) )
	{
		color = fgetc( imageFile );
		if( color  < 192 )
		{
			if( x > ( m_header.xEnd - m_header.xStart ) )
			{
				x = 0;
				y++;
			}
			m_image->setRGB( x++, y, palette[color] );
		}
		else
		{
			length = color - 192;
			color = fgetc( imageFile );
			for ( counter = 0; counter < length; counter++ )
			{
				if( x > ( m_header.xEnd - m_header.xStart ) )
				{
					x = 0;
					y++;
				}
				m_image->setRGB( x++, y, palette[color] );
			}
		}
	}

	fclose( imageFile );

	return m_image;
}

void PCXImage::readHeader( void )
{
	fread(&m_header, sizeof( PCXHeader ), 1, imageFile );
}